var sbold = /<b>/gi;
var ebold = /<\/b>/gi;
var currobj_id;
var load = false;

var xmlhttp;
var response = '';
var sep = ',';
var currentid;
var succ = 1;
var ncotsotienvn_input = 1;
var ncotsotiennt_input = 2;
var ncotsotiennt = 5;
var ncottygia = 6;
var nhapngoaite = 0;
var ndongbd = 2;
var addmode ;
var FormCT = "";

$(document).ready(function() {
    $('.tabs .tab-links a').click(function(e){
        var currentAttrValue = $(this).attr('href');
        $('.tabs ' + currentAttrValue).show().siblings().hide();
        if (FormCT == "")
        {
            FormCT = "Thue"
            $('a#tab1').css("color", "MidnightBlue");
            $('a#tab2').css("color", "red");
        }
        else{
            FormCT = "";
            $('a#tab2').css("color", "MidnightBlue");
            $('a#tab1').css("color", "red");
        }
        //$(this).parent('td').parent('li').addClass('active').siblings().removeClass('active');
        //e.preventDefault();
    });

    $('.datepicker').each(function() {
        $(this).removeClass('hasDatepicker').datepicker();
    });


    $("#ngct").datepicker({dateFormat:"dd/mm/yy"});
    $("#ngaylapct").datepicker({dateFormat:"dd/mm/yy"});
    $("#ngayctcn").datepicker({dateFormat:"dd/mm/yy"});


    $('.selectMenu2').css("width", "200px");
    $('.selectMenu3').css("width", "300px");

    $('#breadcrumb').css("font-size", "1em");

    $('a#CNTMTG').click(function(){
        url = $(this).attr("href");
        var ChiTiet=document.getElementById('ttChiTiet').innerHTML;
        var LoaiTien=document.getElementById('ttLoaiTien').innerHTML;
        var Nam=document.getElementById('ttNam').innerHTML;
        url = url + "?ChiTiet="+ChiTiet+"&&Nam="+Nam+"&&LoaiTien="+LoaiTien;
        $(this).attr('href',url);
    });

    $('input#cancel').click(function(){
        url = $('a#CNTMTG').attr("href");
        var ChiTiet=document.getElementById('ttChiTiet').innerHTML;
        var LoaiTien=document.getElementById('ttLoaiTien').innerHTML;
        var Nam=document.getElementById('ttNam').innerHTML;
        url = url + "?ChiTiet="+ChiTiet+"&&Nam="+Nam+"&&LoaiTien="+LoaiTien;
        location.href = url;

    });

    //$("table#mymain").css("background-color", "#D1E5EB");
    //$("table#head td").css("background-color", "LightGoldenRodYellow");

    //$("table#mymain").css("border", "1px dotted #6E7FC9");
    //$("table#mymain td").css("border", "1px dotted black");
    //$("table#myDetail td").css("border", "1px dotted #6E7FC9");
    $("td.value").css("text-align", "left");


    //$("table#myDetail").css("border", "1px solid #6E7FC9");
    //$("table#myDetail th").css("background-color", "Silver ");
    //$("table#myDetail th").css("color", "RoyalBlue");

    //$("th").css("border", "1px dotted #6E7FC9");

    //$("table#myTotal").css("border", "1px solid black");
    $("table#myTotal td").css("border", "1px solid white");

    //$('.actiondelrow').css("font-size", "0.8em");

    $('.css_corner').css("border-radius", "15px");
    $('.css_corner').css("-moz-border-radius", "21px");
    $('.css_corner').css("-webkit-border-radius", "21px");
    $('.css_corner').css("border", "thin solid #DDDDD0");
    $('.css_corner').css("text-align", "center");
    //$('.css_corner').css("background-color", "#D1E5EB");
    $('.css_corner').css("color", "#9C4147");
    $('.css_corner').css("font-size", "0.8em");


    //$('.title').css("font-family", "ABeeZee") ;
    //$('.title').css("line-height", "1em") ;
    //$('.title').css("font-size", "2em") ;
    //$('.title').css("color", "#458B74") ;
    //$('.title').css("text-shadow", "4px 2px 4px #C2C2C2") ;



    $( "#ngctcn1" ).datepicker({dateFormat:"dd/mm/yy"});
    $( "#ngctcn2" ).datepicker({dateFormat:"dd/mm/yy"});
    $( "#ngctcn" ).datepicker({dateFormat:"dd/mm/yy"});
    $( "#fNgay1" ).datepicker({dateFormat:"dd/mm/yy"});
    $( "#fNgay2" ).datepicker({dateFormat:"dd/mm/yy"});
    $( ".datepicker" ).datepicker({dateFormat:"dd/mm/yy"});



    $("input").keydown(function(){
        //alert(event.keyCode );
        var self = $(this)
            , form = self.parents('form:eq(0)')
            , focusable
            , next
            ;
        if (event.keyCode == 13) {
            focusable = form.find('input').filter(':text');
            next = focusable.eq(focusable.index(this)+1);
            if (next.length) {
                //alert(event.keyCode );
                next.focus();
            } else {
            }
            return false;
        }


    });

    var validator = $("#CTTMTG").validate();
    jQuery("#isstate").blur(function() {

        var states = ['PA', "CA"] // of course you will need to add more
        var in_array = $.inArray(value.toUpperCase(), states);
        if (in_array == -1) {
            return false;
        }else{
            return true;
        }
    });

    jQuery.validator.addMethod('integer', function (value, element, param) {
        return (value != 0) && (value == parseFloat(value, 10));
    }, 'Please enter a non zero integer value!');


});

function DMTraCuu()
{
}

function LoadForm_add(sdong){
    //$('body').css("font-size", "0.8em");
    for (iL= 1; iL<sdong; iL++)
    {
        addnewrow_add();
    }
    document.getElementById("soct").focus();
    hideusd();
}

function showusd(){
    var tags = $('#tygiatk, #lbltygia, #myDetail th:nth-child('+ncotsotiennt+'), #myDetail td:nth-child('+ncotsotiennt+')');
    tags.show();

    var tags = $('#tygiatk, #lbltygia, #myDetail th:nth-child('+ncottygia+'), #myDetail td:nth-child('+ncottygia+')');
    tags.show();
    nhapngoaite = 1;
}

function hideusd(){
    var tags = $('#tygiatk, #lbltygia, #myDetail th:nth-child('+ncotsotiennt+'), #myDetail td:nth-child('+ncotsotiennt+')');
    tags.hide();

    var tags = $('#tygiatk, #lbltygia, #myDetail th:nth-child('+ncottygia+'), #myDetail td:nth-child('+ncottygia+')');
    tags.hide();
    nhapngoaite  = 0;

}

function changeMaNT(id){
    var mant = $('#'+ id).val();
    if (mant == "VND")
    {
        hideusd();
    }
    else{
        showusd();
    }
    tinhtong();
}

function toObject(arr) {
    var rv = {};
    for (var i = 0; i < arr.length; ++i)
        if (arr[i] !== undefined) rv[i] = arr[i];
    return rv;
}

//********nhat---------------
/*'{$sodong}', '{$matk}', '{$mant}', '{$tkduss}', '{$macttkduss}',{$urlS_getTenDMDV},'{$daidienss}','{$diachiss}', '{$lydoss}','{$noidungthuess}', '{$sotienvnss}', '{$sotienntss}','{$urlS_getTenDMTK}', '{$urlS_getTenDMDV}','{$diengiaiss}' /,soctcnss,tenkhss,solgctgss,sotien_tygiass,ma_dvcsss,loaihinhss,kihieumdss,sohdss,soseriss,ngayhdss,makhss,masotss,tenhhss,mathuess,thuesuatss,sotienss,thuess,tongtienss,mavuviecss,
/***
* function LoadForm_edit(sdong, matk, mant, tkduss, macttkduss, urlGettendmDV, daidienss, diachiss,lydoss,noidungthuess,urlGettendmTK,urlGettendmDV,sotienvnss, sotienntss, diengiaiss){
* */
function LoadForm_edit(sdong, matk, mant, tkduss, macttkduss, sotienvnss, sotienntss, diengiaiss, urlGettendmTK,urlGettendmDV ){
    var myObject = {};
    if (mant == "VND")
    {
        hideusd();
    }

    for (iL= 1; iL<sdong; iL++)
    {
        addnewrow_add();
    }

    $('input#print').attr("disabled", false);
    tkdus = tkduss.split(",,,");
    macttkdus = macttkduss.split(",,,");
    sotienvns = sotienvnss.split(",,,");
    sotiennts = sotienntss.split(",,,");
    diengiais = diengiaiss.split(",,,");
    //nhat
    noidungthues = noidungthuess.split(",,,");
    soctcns = soctcnss.split(",,,");
    tenkhs = tenkhss.split(",,,");

    lydos = lydoss.split(",,,");
    diachis = diachiss.split(",,,");
    daidiens = daidienss.split(",,,");

    myObject.tkdus = toObject(tkdus);
    myObject.macttkdus = toObject(macttkdus);
    myObject.sotienvns = toObject(sotienvns);
    myObject.sotiennts = toObject(sotiennts);
    myObject.diengiais = toObject(diengiais);
    myObject.noidungthues = toObject(noidungthues);
    myObject.soctcns = toObject(soctcns);
    myObject.tenkhs = toObject(tenkhs);
    myObject.lydos = toObject(lydos);
    myObject.diachis = toObject(diachis);
    myObject.daidiens = toObject(daidiens);


    fieldstring = "matk - mant - tkdu -  macttkdu - sotienvn - sotiennt - diengiai - noidungthue - soctcn - lydo - diachi - daidien ";

   	document.getElementById("soct").focus();

var x=document.getElementById('myDetail');

cot = 0;
var dataCT = Array();
var fieldCT = Array();

$(".myheaderrow").each(function(i, v){
$(this).find('th#select').each(function(ii, vv){
fieldCT[cot] = $(this).attr("name");
dataCT[cot] = Array();
if (fieldstring.indexOf(fieldCT[cot]) >=0){
dataCT[cot] = Array();
for (i1 =0 ; i1< sdong ; i1++){
name = fieldCT[cot]+'s';
dataCT[cot][i1] = "_"+ myObject[name][i1] ;
//dataCT[cot][i1] = "_"+  eval(fieldCT[cot]+'s['+i1+']');	
}
}else{
//alert(fieldCT[cot] + " chưa cập nhật!");
for (i1 =0 ; i1< sdong ; i1++){
dataCT[cot][i1] = "";
}
}
cot = cot+1;
}); 

$(this).find('th#input').each(function(ii, vv){
fieldCT[cot] = $(this).attr("name");
dataCT[cot] = Array();
if (fieldstring.indexOf(fieldCT[cot]) >=0)
{
for (i1 =0 ; i1< sdong ; i1++){
name = fieldCT[cot]+'s';
dataCT[cot][i1] = myObject[name][i1] ;
if (fieldCT[cot].indexOf("sotien") ==0){
dataCT[cot][i1] = addCommas(dataCT[cot][i1] );
}
}
}
else{
//alert(fieldCT[cot] + " chưa cập nhật!!!");
for (i1 = 0 ; i1< sdong ; i1++ ){
dataCT[cot][i1] = "";
}
}
cot = cot + 1;
}); 
});
var ncotvn = 3;
var ncotnt = 4 ;
var total = 0; totalnt = 0;


for (i1 =0 ; i1< sdong ; i1++){
   var new_row = x.rows[ndongbd+i1];
var sele = new_row.getElementsByTagName('select');
var input = new_row.getElementsByTagName('input');
var div = new_row.getElementsByTagName('div');
var cot = 0;

for (i = 0 ; i< sele.length; i++){
var sele1 = sele[i];
$("#"+sele1.id).val(dataCT[cot][i1]);
cot = cot +1;
}
var sele1 = sele[0];
changeMa(sele1.id, urlGettendmTK);
var sele1 = sele[1];
changeMaCTTK(sele1.id, urlGettendmDV);

for (i = 0 ; i< input.length; i++){
var inp1 = input[i];
$("#"+inp1.id).val(dataCT[cot][i1]);
if (cot == ncotvn)
{
var st = parseFloat((dataCT[cot][i1]).replace(/,/g, ""));
if (st >0 )
{
total +=  st;
}
}

if (cot == ncotnt)
{
var stnt = parseFloat((dataCT[cot][i1]).replace(/,/g, ""))*100000;
if (stnt >0 )
{
totalnt +=  stnt;
}
}

cot = cot + 1;
}
}

if (mant == 'VND')
{
document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ"; 
}
else{
document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")"; 

}

return;
    ///////////////////////////////


    for (i = 0 ; i< a.length; i++){
        var a1 = a[i];
        a1.id += len;
    }

    for (i = 0 ; i< div.length; i++){
        var div1 = div[i];
        div1.innerHTML= '';
    }
    x.appendChild( new_row );
    sele1 = sele[0];
    sele1.focus();
    return;
}

function jgetDV(pkq, url)
{
    if (currobj_id.indexOf('chitiettkdu')==0)
    {
        pmadv = pkq.split('::');
        pma = pmadv[0];
        $("#" + currobj_id).val(pma);
        HideDM();
        changeMaCTTK(currobj_id, url);
    }
    return;
}


function RefeshDM()
{	var e = document.getElementById("DM");
    var ma = e.options[e.selectedIndex].value;
    if (ma == 0)
    {
        document.getElementById('danhmucTK').style.display = 'none';
        document.getElementById('danhmucDV').style.display = 'block';
    }
    else if (ma == 1)
    {
        document.getElementById('danhmucTK').style.display = 'block';
        document.getElementById('danhmucDV').style.display = 'none';

    }
}


function zRefeshDM(danhmucs, tendm)
{
    danhmuc = danhmucs.split(",,,,,");
    document.getElementById('danhmuc').innerHTML  = "<b>"+tendm+"</b><br>";
    for (i = 0; i < danhmuc.length ; ++i)
    {
        document.getElementById('danhmuc').innerHTML  = document.getElementById('danhmuc').innerHTML + "<br>"+ danhmuc[i];
    }
    document.getElementById('danhmuc').innerHTML  = document.getElementById('danhmuc').innerHTML + "<br>";

}

function refreshDMDV(letter, url)
{
    url = url+ "?dmdv_initial="+ letter;
    jQuery.ajax({
        type: "POST",
        url: url,
        cache: false,
        success: function(response)
        {
            //alert(response);
            document.getElementById('danhmucDV_ND').innerHTML = "Các Đơn vị bắt đầu là <b>" + letter+ "</b>:<br>(Nhấn CRL+F để tìm kiếm)<hr>"+ response;

        },

        error: function(data, errorThrown)
        {
            alert('request failed :'+errorThrown);
        }
    });


}


function jgetTK(pkq, url)
{
    //alert(pkq+ url+ currobj_id);
    if (currobj_id.indexOf('tkdu')==0)
    {

        pma = pkq.split('::');
        pma = pma[0];
        $("#" + currobj_id).val(pma);
        HideDM();
        changeMa(currobj_id, url);
    }
    return;
}

function jgetmaTK(pma, pten)
{
    if (currobj_id.indexOf('tkdu')==0)
    {
        var dd = document.getElementById(currobj_id);
        for (var i = 0; i < dd.options.length; i++) {
            if (dd.options[i].text === pma) {
                dd.selectedIndex = i;
                break;
            }
        }
        // lay ra ten
        var x= dd.parentNode;
        var a = x.getElementsByTagName('div')[0];
        a.innerHTML = pten;
    }

}


function jgetmaDV(pma, pten)
{
    if (currobj_id.indexOf('chitiettkdu')==0)
    {
        var dd = document.getElementById(currobj_id);
        for (var i = 0; i < dd.options.length; i++) {
            if (dd.options[i].text === pma) {
                dd.selectedIndex = i;
                break;
            }
        }
        // lay ra ten
        var x= dd.parentNode;
        var a = x.getElementsByTagName('div')[0];
        a.innerHTML = pten;
    }

}


function SetCur(pObj, tkdvs, tkcps)
{
    currobj_id = pObj
    return;

    if (currobj_id.indexOf('tkdu')==0)
    {
        document.getElementById('danhmucTK').style.display = 'block';
        document.getElementById('danhmucDV').style.display = 'none';
    }
    else if (currobj_id.indexOf('chitiettkdu')==0)
    {
        idmatk = currobj_id.replace("chitiettkdu", "tkdu");
        matk = document.getElementById(idmatk).value;
        if (matk.length == 0 )
        {
            alert("Ban chua nhap MATK!" );
            document.getElementById(idmatk).focus();
            return;
        }
        p = tkdvs.indexOf(matk+"-");

        if (p=0 || tkdvs.substr(p-1,1) == '-')
        {

            document.getElementById('danhmucTK').style.display = 'none';
            document.getElementById('danhmucDV').style.display = 'block';
        }
        else
        {
            document.getElementById('danhmucTK').style.display = 'none';
            document.getElementById('danhmucDV').style.display = 'none';


        }
    }
    else
    {
        document.getElementById('danhmucTK').style.display = 'none';
        document.getElementById('danhmucDV').style.display = 'none';
    }


}



function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    //alert(charCode);
    if (charCode == 46 )
    {
        return true;
    }
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}


function EnterMa(id, idHint, aData)
{
    var stk, astk, pos;
    var kq = document.getElementById(id).value.toUpperCase();
    dmtk = aData.split(",");

    for (i = 0; i < dmtk.length; ++i)
    {
        stk = dmtk[i].toUpperCase();
        pos = stk.indexOf(kq);
        if (pos==0)
        {
            astk = stk.split("-");
            document.getElementById(idHint).innerHTML  =  astk[1];
            return;
        }
    }
    document.getElementById(idHint).innerHTML  =  "*M&#227; nh&#7853;p sai ";
}


function close_window() {
    if (confirm("Ban muon ngung cap nhat?")) {
        close();
    }
}



function OnBlurInput(aData, v)
{

    var a = aData.split(",");

    var i;
    var co = 0;
    for (i=0; i<a.length; i++)
    { if (a[i].indexOf(v) >=0)
    {
        co = 1;
        break;
    }

    }


    if (co == 0) {
        document.forms['CTTMTG'].elements['isstate'].focus();
    }

}

function addnew() {
    // Insert a DOM element object
    $('#myDiv').load('http://localhost/duoctu3/templates/acctKT/SDTTForm_add.php');



}

function getmaxid(){
    var x=document.getElementById('myDetail');
    var len = x.rows.length;
    var a = x.getElementsByTagName('a');
    var idbd= a[0].id;
    var maxid ;
    if (a.length == 1)
    {
        maxid = 1;
    }
    else{
        var idkt = a[a.length-1].id;
        maxid = idkt.replace(idbd, "");
        maxid = parseInt(maxid)+1;
    }

    return maxid;
}

function getdong(rId){
    var x=document.getElementById('myDetail');
    var len = x.rows.length;
    var a = x.getElementsByTagName('a');
    for (i=0;i<a.length ; i++)
    {
        if (rId == a[i].id)
        {
            row = i + ndongbd;
        }
    }
    return row;
}


function addnewrow_edit(tkdus, macttkdus, sotiennts, sotienvns, diengiais, sotienntss)
{
    // alert(sotienntss);
    var x=document.getElementById('myDetail');
    var new_row = x.rows[2].cloneNode(true);

    var len = getmaxid();
    var ncot = new_row.cells.length;

    var sele1 = new_row.cells[0].getElementsByTagName('select')[0];
    sele1.id += len;

    //tkdus = "_"+tkdus;
    //$("#"+sele1.id).val("_1122"); khoong dungduoc
    {//tkdus
        for (var i = 0; i < sele1.options.length; i++) {
            if ((sele1.options[i].text).indexOf(tkdus) == 0) {
                sele1.selectedIndex = i;
                break;
            }
        }
    }


    sele1 = new_row.cells[1].getElementsByTagName('select')[0];
    sele1.id += len;
    //$("#"+sele1.id).val("_"+macttkdus);
    {//macttkdu
        for (var i = 0; i < sele1.options.length; i++) {
            if ((sele1.options[i].text).indexOf(macttkdus) == 0) {
                sele1.selectedIndex = i;
                break;
            }
        }
    }

    var cot = 2;
    if (sotienntss !=-1)
    {
        var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
        cot = cot +1;
        input1.value = 	addCommas(sotiennts);

    }

    var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
    cot = cot +1;
    {//sotienvn
        input1.id += len;
        input1.value = addCommas(sotienvns) ;
    }

    var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
    cot = cot+1;
    {//sotienvn
        input1.id += len;
        input1.value = diengiais;

    }

    var a1 = new_row.getElementsByTagName('a')[0];
    a1.id += len;

    var inp1 = new_row.getElementsByTagName('div')[0];
    inp1.innerHTML= '';

    var inp1 = new_row.getElementsByTagName('div')[1];
    inp1.innerHTML= '';

    x.appendChild( new_row );
}



function addnewrow_add()
{
    ///
    tId = "myDetail";
    var x=document.getElementById(tId);
    var new_row = x.rows[2].cloneNode(true);

    var sele = new_row.getElementsByTagName('select');
    var input = new_row.getElementsByTagName('input');
    var div = new_row.getElementsByTagName('div');
    var a = new_row.getElementsByTagName('a');
    var len = getmaxid();
    for (i = 0 ; i< sele.length; i++){
        var sele1 = sele[i];
        sele1.id += len;
        $("#"+sele1.id).val();
    }

    for (i = 0 ; i< input.length; i++){
        var inp1 = input[i];
        inp1.id += len;
        inp1.value = '';
    }

    for (i = 0 ; i< a.length; i++){
        var a1 = a[i];
        a1.id += len;
    }

    for (i = 0 ; i< div.length; i++){
        var div1 = div[i];
        div1.innerHTML= '';

    }

    x.appendChild( new_row );
    sele1 = sele[0];
    sele1.focus();

    ///
    tId = "myDetailThue";
    var x=document.getElementById(tId);
    var new_row = x.rows[2].cloneNode(true);

    var sele = new_row.getElementsByTagName('select');
    var input = new_row.getElementsByTagName('input');
    var div = new_row.getElementsByTagName('div');
    var a = new_row.getElementsByTagName('a');
    for (i = 0 ; i< sele.length; i++){
        var sele1 = sele[i];
        sele1.id += len;
        $("#"+sele1.id).val();
    }

    for (i = 0 ; i< input.length; i++){
        var inp1 = input[i];
        inp1.id += len;
        inp1.value = '';
    }

    for (i = 0 ; i< a.length; i++){
        var a1 = a[i];
        a1.id += len;
    }

    for (i = 0 ; i< div.length; i++){
        var div1 = div[i];
        div1.innerHTML= '';

    }

    x.appendChild( new_row );

    ///

    $('.datepicker').each(function() {
        $(this).removeClass('hasDatepicker').datepicker();
    });
    return;

}

function addnewrow_addLuu()
{
    //alert(FormCT);""; Thue
    var x=document.getElementById('myDetail');
    var new_row = x.rows[2].cloneNode(true);
    var sele = new_row.getElementsByTagName('select');
    var input = new_row.getElementsByTagName('input');
    var div = new_row.getElementsByTagName('div');
    var a = new_row.getElementsByTagName('a');
    var len = getmaxid();



    for (i = 0 ; i< sele.length; i++){
        var sele1 = sele[i];
        sele1.id += len;
        $("#"+sele1.id).val();
    }

    for (i = 0 ; i< input.length; i++){
        var inp1 = input[i];
        inp1.id += len;
        inp1.value = '';
    }

    for (i = 0 ; i< a.length; i++){
        var a1 = a[i];
        a1.id += len;
    }

    for (i = 0 ; i< div.length; i++){
        var div1 = div[i];
        div1.innerHTML= '';
    }
    x.appendChild( new_row );
    sele1 = sele[0];
    sele1.focus();
    return;


    var x=document.getElementById('myDetail');
    var new_row = x.rows[2].cloneNode(true);

    var len = getmaxid();
    var ncot = new_row.cells.length;
    var sele1 = new_row.cells[0].getElementsByTagName('select')[0];
    sele1.id += len;
    sele1 = new_row.cells[1].getElementsByTagName('select')[0];
    sele1.id += len;

    for (i = 2 ; i< ncot - 2; i++)
    {
        var inp1 = new_row.cells[i].getElementsByTagName('input')[0];
        inp1.id += len;
        inp1.value = '';
    }
    var inp1 = new_row.cells[ncot-2].getElementsByTagName('input')[0];
    inp1.id += len;

    var a1 = new_row.getElementsByTagName('a')[0];
    a1.id += len;

    var inp1 = new_row.getElementsByTagName('div')[0];
    inp1.innerHTML= '';

    var inp1 = new_row.getElementsByTagName('div')[1];
    inp1.innerHTML= '';

    x.appendChild( new_row );
    sele1 = new_row.cells[0].getElementsByTagName('select')[0];
    sele1.focus();

}




function delerow(rId,tId)
{
    var parentCell = $("#"+rId).parent('td');
    parentCell = parentCell.parent('tr');
    $(parentCell).css("background","DarkGray");

    var dong =  getdong(rId);
    if (dong == ndongbd)
    {
        alert("Khong xoa duoc!");
        $(parentCell).css("background","");
    }
    else{
        if (confirm("Ban muon xoa dong nay khong?"))
        {
            if (tId == "myDetail"){
                tId2 = "myDetailThue";
            }
            else{
                tId2 = "myDetail";
            }

            document.getElementById(tId).deleteRow(dong);
            document.getElementById(tId2).deleteRow(dong);
            tinhtong();
        }
        else{
            $(parentCell).css("background","");}
    }
    return;
}

function delerowcu(rId)
{
    var parentCell = $("#"+rId).parent('td');
    parentCell = parentCell.parent('tr');
    $(parentCell).css("background","DarkGray");

    var dong =  getdong(rId);
    if (dong == ndongbd)
    {
        alert("Khong xoa duoc!");
        $(parentCell).css("background","");
    }
    else{
        if (confirm("Ban muon xoa dong nay khong?"))
        {
            document.getElementById("myDetail").deleteRow(dong);
            tinhtong();
        }
        else{
            $(parentCell).css("background","");}
    }
    return;
}


function tinhtongAll(x, dong, cotnt, cotvn, tygia)
{
    if (x==null)
    {
        x=document.getElementById('myDetail');
    }
    var len = x.rows.length;

    if (tygia!==null)
    {
        tygia = document.getElementById('tygia').value;
        tygia = parseFloat(tygia.replace(/,/g, ""));
    }
    var totalvn = 0; var totalnt = 0;

    for (i = dong ; i< len; i++)
    {
        var row = x.rows[i];
        var val = row.getElementsByTagName("input");

        if (cotnt >=0)
        {
            st = val[cotnt].value;
            stnt = parseFloat(st.replace(/,/g, ""))*100;
            if (stnt >0 )
            {
                totalnt +=  stnt;
            }
        }

        st = val[cotvn].value;
        if (tygia !== null)
        {
            stvn = stnt * tygia;
            val[cotvn].value = addCommas(stvn);

        }
        else
        {
            stvn = parseFloat(st.replace(/,/g, ""));
        }

        if (stvn >0 )
        {
            totalvn +=  stvn
        }

    }

    document.getElementById("totalNT").innerHTML = addCommas(totalnt/100);
    document.getElementById("total").innerHTML = addCommas(totalvn);

}



function addnewrow2()
{
    rowNum =1;
    var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
    jQuery('#myTable').append(row);
    frm.add_qty.value = '';
    frm.add_name.value = '';
}



function loadXMLDoc(url,cfunc)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=cfunc;
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}

function zShowMATK(str)
{
    loadXMLDoc("gethint.php?q="+str,function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    });
}

function zzShowMATK(str)
{
    if (str.length==0)
    {
        document.getElementById("txtHint").innerHTML="iiiiiiii";
        return;
    }

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","http://localhost/duoctu3/classes/acct/js/gethint.php?q="+str,true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send();
}


function validNgay(nStr, nid, year)
{

//	var dt1   = parseInt(nStr.substring(0,2));
//	var mon1  = parseInt(nStr.substring(3,5));
//	var yr1   = parseInt(nStr.substring(6,10));
//	var ngay = new Date(yr1, mon1-1, dt1);
//
//	if (isNaN(ngay))
//	{
//		document.getElementById(nid).focus();
//		return;
//	}

    //document.getElementById(nid).value  = addCommas(nStr);
}


function validTyGia(nStr, nid)
{
    document.getElementById(nid).value  = addCommas(nStr);
}

function validnumber(nStr, nid)
{
    nStr += '';
    x = nStr.split('.');
    if (x.length >2)
    {
        alert("Nhập số chưa đúng");
        document.getElementById(nid).focus();
        return;
    }

    document.getElementById(nid).value  = addCommas(nStr);
}


function validSoTienVN(nStr, nid, ncot)
{
    document.getElementById(nid).value  = addCommas(nStr);
    var nidNT = nid.replace('vn', 'nt');
    var nidTG = nid.replace('sotienvn', 'tygia');
    tinhtg(nid, nidNT, nidTG);
    tinhtong();

}


function validSoTienNT(nStr, nid, ncot)
{
    // tinh lai so tien VN:
    //var st1 = parseFloat(st.replace(/,/g, ""));
    nStr += '';
    x = nStr.split('.');
    if (x.length >2)
    {
        alert("Nhập số chưa đúng");
        document.getElementById(nid).focus();
        return;
    }
    document.getElementById(nid).value  = addCommas(nStr);


    var nidVN = nid.replace('nt', 'vn');
    var nidTG = nid.replace('sotiennt', 'tygia');
    tinhtg(nidVN, nid, nidTG);
    tinhtong();

}

function tinhtg(nidVN, nidNT, nidTG){
    var sotienvn = document.getElementById(nidVN).value ;
    sotienvn = parseFloat(sotienvn.replace(/,/g, ""));
    var sotiennt = document.getElementById(nidNT).value ;
    sotiennt = parseFloat(sotiennt.replace(/,/g, ""));

    if (sotiennt == 0 || isNaN(sotiennt))
    {
        document.getElementById(nidTG).value  = "";
    }
    else{
        var tygia = sotienvn/sotiennt;

        document.getElementById(nidTG).value  = addCommas(tygia);
    }


}


function addCommas(nStr, nid)
{
    if (isNaN(nStr))
    {
        return nStr;
    }
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1].substr(0,2) : '';
    //alert(nStr+"---"+x2);
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + sep + '$2');
    }
    return x1 + x2;
}


function tinhtongn(tId)
{
    ncot = ncotsotienvn_input;
    ncotnt = ncotsotiennt_input;
    var mant = $('#mant').val();
    mant = mant.trim();
    var x=document.getElementById(tId);
    var len = x.rows.length;
    var total = 0; totalnt = 0;
    for (i = 2 ; i< len; i++)
    {
        var row = x.rows[i];
        //var cell= row.cells;
        var val = row.getElementsByTagName("input");
        //if (val.length >3)
        {
            var st = val[ncot].value;
            var stnt = val[ncotnt].value;

            var st1 = parseFloat(st.replace(/,/g, ""));
            if (st1 >0 )
            {
                total +=  st1
            }

            stnt = parseFloat(stnt.replace(/,/g, ""))*100000;
            if (stnt >0 )
            {
                totalnt +=  stnt;
            }


        }
    }
    if (mant == 'VND')
    {
        document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ";
    }
    else{
        document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")";

    }

}

function tinhtong()
{
    ncot = ncotsotienvn_input;
    ncotnt = ncotsotiennt_input;
    var mant = $('#mant').val();
    mant = mant.trim();
    var x=document.getElementById('myDetail');
    var len = x.rows.length;
    var total = 0; totalnt = 0;
    for (i = 2 ; i< len; i++)
    {
        var row = x.rows[i];
        //var cell= row.cells;
        var val = row.getElementsByTagName("input");
        //if (val.length >3)
        {
            var st = val[ncot].value;
            var stnt = val[ncotnt].value;

            var st1 = parseFloat(st.replace(/,/g, ""));
            if (st1 >0 )
            {
                total +=  st1
            }

            stnt = parseFloat(stnt.replace(/,/g, ""))*100000;
            if (stnt >0 )
            {
                totalnt +=  stnt;
            }


        }
    }
    if (mant == 'VND')
    {
        document.getElementById('total').innerHTML = "Tổng phát sinh:  &nbsp&nbsp"+ addCommas(total)+ "VNĐ";
    }
    else{
        document.getElementById('total').innerHTML = "Tổng phát sinh: &nbsp&nbsp"+ addCommas(total)+ "VNĐ (" + addCommas(totalnt/100000)+ mant+")";

    }

}

function ShowMATK(q,dmtk)
{
    if (q.length==0)
    {
        document.getElementById("txtHint").innerHTML="H&#227;y nh&#7853;p M&#227; TK";
        return;
    }

    var hint="";
    var nhap="";
    var stk = "";

    dmtk = dmtk.split(",");
    q=q.toLowerCase();
    len=q.length;
    var pos = -1;


    for (i = 0; i < dmtk.length; ++i)
    {
        stk = dmtk[i].toLowerCase();
        pos = stk.indexOf(q);
        if (pos ==0)
        {
            if (hint=="")
            {
                hint = "<a onclick=\"getMATK('" + dmtk[i]+  "')"+ "\">"+dmtk[i]+"</a>";
            }
            else
            {
                hint = hint+"</br><a onclick=\"getMATK('" + dmtk[i]+  "')"+ "\">"+dmtk[i]+"</a>";

            }
        }
    }
    document.getElementById("txtHint").innerHTML=hint;

}

function getMATK(q)
{
    document.getElementById("matk").value=q;
    document.getElementById("txtHint").innerHTML="";

}



function ShowHint(q,aData, txtHint, txtMa, ngandong )
{
    var x=document.getElementById(txtMa);
    x = x.parentNode;
    var a = x.getElementsByTagName('div')[0];


    if (q.length==0)
    {
        //document.getElementById(txtHint).innerHTML="H&#227;y nh&#7853;p M&#227; ";
        return;
    }

    var hint="";
    var ten = "";
    var stk = "";
    var ngandong = '&nbsp; &nbsp; &nbsp;'

    //aData = aData.replace(sbold, "");
    //aData = aData.replace(ebold, "");

    dmtk = aData.split(",");
    q=q.toLowerCase();
    var pos = -1;

    var nhap = "";
    for (i = 0; i < dmtk.length; ++i)
    {
        stk = dmtk[i].toLowerCase();
        //stk = stk.replace(sbold, "");
        //stk = stk.replace(ebold, "");
        nhap = nhap+ stk;

        pos = stk.indexOf("<b>"+q);
        if (pos ==0)
        {
            if (hint=="")
            {
                hint = "<i>"+dmtk[i]+"</i>";
            }
            else
            {
                //hint = hint+ngandong+ "<a onclick=\"getMA('" + dmtk[i]+  "','"+txtMa+"',"+ "'"+ txtHint+"')"+ "\">"+dmtk[i]+"</a>";
                hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

            }
        }
    }
    //alert(hint);


    if (hint=="")
    {
        for (i = 0; i < dmtk.length; ++i)
        {
            if (hint=="")
            {
                hint = "<i>"+dmtk[i]+"</i>";
            }
            else
            {
                hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

            }
        }
    }

    //document.getElementById(txtHint).innerHTML=hint;
    a.innerHTML= hint;
}



function zShowHintCTTK(q,aDataLoaiTK, aDataDV, aDataCP, txtMa, ngandong )
{

    var hint="";
    var ten = "";
    var stk = "";
    var ngandong = '&nbsp; &nbsp; &nbsp;'
    var idmatk, idsotienvn ;
    var idmatk_value ;


    var x=document.getElementById(txtMa);
    x = x.parentNode;
    var a = x.getElementsByTagName('div')[0];

    if (q.length==0)
    {
        a.innerHTML="";

        return;
    }

    /// loai tai khoan:
    //lay tai khoan du:
    idmatk = txtMa.replace("chitiettkdu", "tkdu");
    idsotienvn = txtMa.replace("chitiettkdu", "sotienvn");

    idmatk_value =document.getElementById(idmatk).value;

    if (idmatk_value.length == 0)
    {
        document.getElementById(txtMa).value = "";
        document.getElementById(idmatk).focus();
        a.innerHTML= "**Mã TK kh&#244;nng &#273;&#432;&#7907;c tr&#7889;ng";
        return;
    }

    /// lay danh muc tuong ung
    alert(idmatk_value);

    dmtkLoai = aDataLoaiTK.split(",");
    var inpos = dmtkLoai.indexOf(idmatk_value+"-DV");
    if (inpos>=0)
    {
        dmtk = aDataDV.split(",");
    }
    else
    {
        inpos = dmtkLoai.indexOf(idmatk_value+"-CP");
        if (inpos>=0)
        {
            dmtk = aDataCP.split(",");
        }
        else
        {
            document.getElementById(txtMa).value = "";
            //document.getElementById(idsotienvn).focus();
            a.innerHTML= "";
            return;

        }

    }

    q=q.toLowerCase();
    var pos = -1;

    for (i = 0; i < dmtk.length; ++i)
    {
        stk = dmtk[i].toLowerCase();
        pos = stk.indexOf(q);
        if (pos ==0)
        {
            if (hint=="")
            {
                hint = "<i>"+dmtk[i]+"</i>";
            }
            else
            {
                //hint = hint+ngandong+ "<a onclick=\"getMA('" + dmtk[i]+  "','"+txtMa+"',"+ "'"+ txtHint+"')"+ "\">"+dmtk[i]+"</a>";
                hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

            }
        }
    }

    if (hint=="")
    {
        for (i = 0; i < dmtk.length; ++i)
        {
            if (hint=="")
            {
                hint = "<i>"+dmtk[i]+"</i>";
            }
            else
            {
                hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

            }
        }
    }

    //document.getElementById(txtHint).innerHTML=hint;
    a.innerHTML= hint;
}



function changeMaCTTK(id, url)
{

    var e = document.getElementById(id);
    var ma = $("#" + id).val();
    ma = ma.substring(1);
    url = url+ "?dmdv_madv="+ ma;

    jQuery.ajax({
        type: "POST",
        url: url,
        cache: false,
        success: function(response)
        {
            var akq = response.split("---");
            if (id.indexOf("chitiet")>=0)
            {
                x = e.parentNode;
                var a = x.getElementsByTagName('div')[0];
                a.innerHTML= akq[0];
            }
            else{
                var odiachi = document.getElementById('diachi');
                var odaidien = document.getElementById('daidien');
                if ((odaidien.value).trim() ==""){
                    odaidien.value = akq[3];
                }

                if ((odiachi.value).trim() =="")
                {
                    odiachi.value = akq[2];
                    document.getElementById("lydo").focus();
                }

            }
        },

        error: function(data, errorThrown)
        {
            alert('request failed :'+errorThrown);
        }
    });
}

function changeMa(id, url)
{
    var e = document.getElementById(id);
    var ma = $("#" + id).val();
    ma = ma.substring(1);

    url = url+ "?dmtk_matk="+ String(ma);
    x = e.parentNode;
    var a = x.getElementsByTagName('div')[0];


    jQuery.ajax({
        type: "POST",
        url: url,
        cache: false,
        success: function(response)
        {
            a.innerHTML= response;
        },

        error: function(data, errorThrown)
        {
            alert('request failed :'+errorThrown);
        }
    });
}

function changeMaTQ(id, url)
{
    var e = document.getElementById(id);
    var ma = e.options[e.selectedIndex].text;
    url = url+ "?ma="+ ma;
    x = e.parentNode;
    var a = x.getElementsByTagName('div')[0];


    jQuery.ajax({
        type: "POST",
        url: url,
        cache: false,
        success: function(response)
        {
            a.innerHTML= response;
        },

        error: function(data, errorThrown)
        {
            alert('request failed :'+errorThrown);
        }
    });
}

function ExitMa(id, aData)
{
    var kq = document.getElementById(id).value.toUpperCase() +"-";
    var pos = aData.indexOf(kq);

    if (pos <0 )
    {
        alert("Hay nhap ma dung!");
        document.getElementById(id).value = "";
        document.getElementById(id).focus();

    }
    else
    {
        document.getElementById(id).value = kq.substr(0,kq.length-1);
    }
}


function ExitMaCTTK(id, aDatadv, tkdvs, aDatacp, tkcps)
{
    var kq = document.getElementById(id).value.toUpperCase(); //+"-";
    kq	= kq.replace(/^\s+|\s+$/g, '');
    kq = kq +"-";
    idmatk = id.replace("chitiettkdu", "tkdu");
    matk = document.getElementById(idmatk).value;
    p = tkdvs.indexOf(matk+"-");

    if (p=0 || tkdvs.substr(p-1,1) == '-')   // tk loai cong no
    {
        var pos = aDatadv.indexOf(kq);
        if (pos <0 )
        {
            alert("Hay nhap ma don vi dung!");
            document.getElementById(id).value = "";
            document.getElementById(id).focus();
        }
        else
        {
            document.getElementById(id).value = kq.substr(0,kq.length-1);
        }
    }
    else
    {
        p = tkcps.indexOf(matk+"-");
        if (p=0 || tkcps.substr(p-1,1) == '-')   // tk loai chi phi
        {
            var pos = aDatacp.indexOf(kq);
            if (pos <0 )
            {
                alert("Hay nhap ma chi phi dung!");
                document.getElementById(id).value = "";
                document.getElementById(id).focus();

            }
            else
            {
                document.getElementById(id).value = kq.substr(0,kq.length-1);
            }
        }
        else
        {   // tk khong chi tiet
            if (kq.length >0)
            {
                alert("Day la TK khong chi tiet");
                document.getElementById(id).value = "";

            }

        }
    }

}


function zExitMa(id, idHint, aData)
{
    var x=document.getElementById(id);
    x = x.parentNode;


    var a = x.getElementsByTagName('div')[0];
    var stk, astk, pos;
    var kq = document.getElementById(id).value.toUpperCase();


    //aData = aData.replace(sbold, "");
    //aData = aData.replace(ebold, "");
    dmtk = aData.split(",");


    for (i = 0; i < dmtk.length; ++i)
    {
        stk = dmtk[i].toUpperCase();
        pos = stk.indexOf(kq);
        if (pos ==0 )
        {
            astk = stk.split("-");
            document.getElementById(id).value = astk[0];
            //document.getElementById(idHint).innerHTML  =  astk[1];
            a.innerHTML  =  astk[1].toLowerCase();;
            return;
        }
    }
    alert("Hay nhap ma dung ka dsadsad");
    document.getElementById(id).value = kq;
    document.getElementById(id).focus();
    //document.getElementById(idHint).innerHTML  =  "Hay nhap ma dung";
    a.innerHTML  =  "Hay nhap ma dung";
}


//function ShowHintCTTK(q,aDataLoaiTK, aDataDV, aDataCP, txtMa, ngandong )
function zExitMaCTTK(id, aDataLoaiTK, aDataDV, aDataCP)
{

    currentid = id;
    var x=document.getElementById(id);
    x = x.parentNode;
    var a = x.getElementsByTagName('div')[0];

    var stk, astk, pos;
    var kq = document.getElementById(id).value.toUpperCase();

    /// loai tai khoan:
    //lay tai khoan du:
    var idmatk = id.replace("chitiettkdu", "tkdu");
    var idmatk_value =document.getElementById(idmatk).value;

    if (idmatk_value.length == 0)
    {
        document.getElementById(txtMa).value = "";
        //document.getElementById(idmatk).focus();
        a.innerHTML= "";
        return;
    }

    /// lay danh muc tuong ung
    dmtkLoai = aDataLoaiTK.split(",");
    var inpos = dmtkLoai.indexOf(idmatk_value+"-DV");
    if (inpos>=0)
    {
        aDataDV = aDataDV.replace(sbold, "");
        aDataDV = aDataDV.replace(ebold, "");
        dmtk = aDataDV.split(",");
    }
    else
    {
        inpos = dmtkLoai.indexOf(idmatk_value+"-CP");
        if (inpos>=0)
        {
            aDataCP = aDataCP.replace(sbold, "");
            aDataCP = aDataCP.replace(ebold, "");
            dmtk = aDataCP.split(",");
        }
        else
        {
            document.getElementById(txtMa).value = "";
            //document.getElementById(idsotienvn).focus();
            a.innerHTML= "";
            return;

        }

    }



    for (i = 0; i < dmtk.length; ++i)
    {
        stk = dmtk[i].toUpperCase();
        pos = stk.indexOf(kq);
        if (pos==0)
        {
            astk = stk.split("-");
            document.getElementById(id).value = astk[0];
            //document.getElementById(idHint).innerHTML  =  astk[1];
            a.innerHTML  =  astk[1].toLowerCase();;
            return;
        }
    }

    alert("Hay nhap ma dung");
    document.getElementById(id).value = kq;
    document.getElementById(id).focus();
    //document.getElementById(idHint).innerHTML  =  "Hay nhap ma dung";
    a.innerHTML  =  "Hay nhap ma dung";

}







function getMA(q, txtMa, txtHint)
{
    var subdata = q.split("-");

    document.getElementById(txtMa).value=subdata[0];
    document.getElementById(txtHint).innerHTML=subdata[1];

}

function testFieldNumber(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field)) {
        // Case of error
        field.value = "";
    }
}

function UpdateRecord(host, username, password, databaseName, year, urlupdate  )
{
    var matk=document.getElementById('matk').value;
    var mant=document.getElementById('mant').value;
    var madv = document.getElementById('madv').value;
    var dknont = document.getElementById('dknont').value;
    var dknovn = document.getElementById('dknovn').value;
    jQuery.ajax({
        type: "POST",
        url: urlupdate,
        data: {host: host, username: username, password: password, databaseName: databaseName, year: year, matk:matk },
        cache: false,
        success: function(response)
        {

            alert("Ghi xong!");

        },

        error: function(data, errorThrown)
        {
            alert('request failed :'+errorThrown);
        }
    });
}




function PrintCT(idphieu, nam, noco, url)
{
    url = url+"?idphieu="+idphieu+"&&noco="+noco+"&&nam="+nam;
    var win = window.open(url, '_blank');
}

function PrintCT_CE(idphieu, nam, noco, url)
{
    if (idphieu=="")
    {
        idphieu = $('div#idphieu').html();
        idphieu = idphieu.trim();
    }

    url = url+"?idphieu="+idphieu+"&&noco="+noco+"&&nam="+nam;
    var win = window.open(url, '_blank');
}

function isValidDate3(d) {
    if ( Object.prototype.toString.call(d) === "[object Date]" ) {
        if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return false;
    }
}


function validdate(nStr) {

}

function isValidDate(y, m, d) {
    if (m>12 || m<1)
    {
        alert("Nhập tháng không đúng!");
        return false;
    }


    switch (m)
    {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            if (d>0 && d<32 )
            {
                return true;
            }
            break;

        case 4:
        case 6:
        case 9:
        case 11:
            if (d>0 && d<31 )
            {
                return true;
            }
            break;
        case 2:
            if (d>0 && d<29 )
            {
                return true;
            }
            break;

        default:
            alert('Nhập ngày không đúng');
            return false;

    }
    return false;


}


function InsCTTMTG(pnew, url, journalid,  year, mant, matk, mact, noco, urlupdate, urlmain )
{

    if ($("input#save").val() == "Thêm mới")
    {
        ngct = $('input#ngct').val();
        ngaylapct = $('input#ngaylapct').val();
        ma_dk  = $('input#ma_dk').val();
        ma_dvcs = $('input#ma_dvcs').val();
        tk = $('select#tk').val();
        mant = $('select#mant').val();

        $('input:text').val("");
        $('select').val(0);
        $('select#tk').val(tk);
        $('select#mant').val(mant);

        $('input#ngct').val(ngct);
        $('input#ngaylapct').val(ngaylapct);
        $('input#ma_dk').val(ma_dk);
        $('input#ma_dvcs').val(ma_dvcs);


        $('input#print').attr("disabled", true);
        $('input#save').attr("value", "Ghi lại");
        $('input#edit').attr("disabled", true);
        //$("select.selectMenu").attr('selectedIndex',0);
        //$("select.selectMenu2").attr('selectedIndex',0);
        $('div.selectMenu').html("");

        document.getElementById("total").innerHTML = "";
        var x=document.getElementById('myDetail');
        var a = x.getElementsByTagName('a');
        var sd = a.length ;
        for (i=ndongbd ;i<sd ; i++){
            document.getElementById("myDetail").deleteRow(3);

        }
        document.getElementById('soct').focus();
        addmode = "add";
        return;
    }

    if (pnew == 'new')
    {
        var win = window.open(url, '_blank');
    }

    var dataMain = Array();
    var fieldMain = Array();
    var dataCT = Array();
    var fieldCT = Array();
    var cot = 0;
    var cotCT = 0;


    //---------nhat-------------
    var dataThue = Array();
    var fieldThue = Array();
    //---------end-------------

    // kiem tra ngay chung tu
    var ngct=document.getElementById('ngct').value;
    var dt1   = parseInt(ngct.substring(0,2));
    var mon1  = parseInt(ngct.substring(3,5));
    var yr1   = parseInt(ngct.substring(6,10));
    if (yr1 != year)
    {
        alert("Ban nhap nam chua dung!");
        document.getElementById('ngct').focus();
        return;
    }
    var ngay = yr1+"/"+ mon1+"/" + dt1;
    var test = isValidDate(yr1, mon1, dt1);
    if (test== "false")
    {
        return;
    }


    $("#mymain").each(function(i, v){
        $(this).find('select').each(function(ii, vv){
            giatri = $("option:selected", this).text();
            //field = $("option:selected", this).name();
            giatri = giatri.split("::");
            dataMain[cot] = String(giatri[0]);
            fieldMain[cot] = vv.id;
            //alert(fieldMain[cot]+"="+ dataMain[cot]);
            cot = cot+1;

        });

        $(this).find('input').each(function(ii, vv){
            //alert(vv.id);
            fieldMain[cot] = vv.id;
            if (fieldMain[cot].indexOf("sotien") ==0)
            {
                var st = $(this).val();
                var st1 = parseFloat(st.replace(/,/g, ""));
                if (!isNaN(st1))
                {
                    dataMain[cot] = st1;
                }
                else
                {
                    dataMain[cot] = "";
                }
            }
            else
            {
                dataMain[cot]= $(this).val();
            }
            cot = cot+1;


        });
    })
    // xong phan main

    cot = 0;
    $(".myheaderrow").each(function(i, v){
        $(this).find('th#select').each(function(ii, vv){
            fieldCT[cot] = $(this).attr("name");
            cot = cot+1;
        });
        $(this).find('th#input').each(function(ii, vv){
            fieldCT[cot] = $(this).attr("name");
            //alert(fieldCT[cot]);
            cot = cot+1;
        });
    })


    $(".mydatarow").each(function(i, v){
        cot = 0;
        dataCT[i] = Array();
        $(this).find('select').each(function(ii, vv){
            giatri = $("option:selected", this).text();
            giatri = giatri.split("::");
            dataCT[i][cot] = String(giatri[0]);
            cot = cot +1;
        });


        $(this).find('input').each(function(ii, vv){
            if (fieldCT[cot].indexOf("sotien") ==0)
            {
                var st = $(this).val();
                var st1 = parseFloat(st.replace(/,/g, ""));
                if (!isNaN(st1))
                {
                    dataCT[i][cot] = st1;
                }
                else
                {
                    dataCT[i][cot] = "";
                }
                cot = cot+1;
            }
            else
            {
                dataCT[i][cot] = $(this).val();
                //alert(i+""+ dataCT[i][cot]);
                cot = cot+1;
            }
        });
    })

    //-------------nhat----------------------------
    cot = 0;
    $(".myheaderrowthue").each(function(i, v){
        $(this).find('th#select').each(function(ii, vv){
            fieldThue[cot] = $(this).attr("name");
            cot = cot+1;
        });
        $(this).find('th#input').each(function(ii, vv){
            fieldThue[cot] = $(this).attr("name");
            cot = cot+1;
        });
    })
    $(".mydatarowthue").each(function(i, v){
        cot = 0;
        dataThue[i] = Array();
        $(this).find('select').each(function(ii, vv){
            giatri = $("option:selected", this).text();
            giatri = giatri.split("::");
            dataThue[i][cot] = String(giatri[0]);
            cot = cot +1;
        });
        $(this).find('input').each(function(ii, vv){
            if (fieldThue[cot].indexOf("sotien") ==0)
            {
                var st = $(this).val();
                var st1 = parseFloat(st.replace(/,/g, ""));
                if (!isNaN(st1))
                {
                    dataThue[i][cot] = st1;
                }
                else
                {
                    dataThue[i][cot] = "";
                }
                cot = cot+1;
            }
            else
            {
                dataThue[i][cot] = $(this).val();
                cot = cot+1;
            }
        });
    })
    //-------------end-----------------------------


    idphieu = $('div#idphieu').html();
    if (idphieu)
    {
        addmode="edit";
    }
    else{
        addmode="add";
    }




    jQuery.ajax({
        type: "POST",
        url: urlupdate,
        data: {journalid:journalid,  year:year,  dataMain: dataMain, fieldMain: fieldMain, dataCT: dataCT, fieldCT: fieldCT,dataThue: dataThue, fieldThue: fieldThue, mact:mact, noco:noco, idphieu: idphieu, addmode: addmode},
        cache: false,
        success: function(response)
        {
            alert(response);
            if (response.substring(0,1) == "2")
            {
                alert("Khong co du lieu!");
            }
            else if (response.substring(0,1) == "1")
            {
                alert("Co loi du lieu, mau tin khong ghi duoc!");

            }
            else
            {
                if (idphieu == "")
                {
                    var kq = response.split(":::");
                    $('div#idphieu').html(kq[1]);
                    $('input#print').attr("disabled", false);
                    $('input#save').attr("value", "Thêm mới");
                }
                else
                {
                    // alert("Da ghi xong!");
                }
                $('div#action').html("Xem chứng từ");
                $('input#save').attr("value", "Thêm mới");
                $('input#edit').attr("disabled", false);
                $('input#edit').attr("value", "Sửa");
            }
        },

        error: function(data, errorThrown)
        {
            alert('request failed :'+errorThrown);
        }
    });


    return;

    if ($("input#save").val() == "Thêm mới")
    {
        ngct = $('input#ngct').val();
        $('input:text').attr("value", "");
        $('input#ngct').attr("value", ngct);

        $('input#print').attr("disabled", true);
        $('input#save').attr("value", "Ghi lại");
        $('input#edit').attr("disabled", true);
        $("select.selectMenu").attr('selectedIndex',0);
        $("select.selectMenu2").attr('selectedIndex',0);
        $('div.selectMenu').html("");
        document.getElementById("total").innerHTML = "";
        if ($("#totalNT").length){ // do something here }
            document.getElementById("totalNT").innerHTML = "";
        }

        var x=document.getElementById('myDetail');
        var a = x.getElementsByTagName('a');
        var sd = a.length ;
        for (i=2;i<sd ; i++){
            document.getElementById("myDetail").deleteRow(3);

        }

        document.getElementById('soct').focus();
        return;
    }

    if (pnew == 'new')
    {
        var win = window.open(url, '_blank');
    }
    var data = Array();
    var cautruc = Array();

    var soct=document.getElementById('soct').value;
    var ngct=document.getElementById('ngct').value;

    var dt1   = parseInt(ngct.substring(0,2));
    var mon1  = parseInt(ngct.substring(3,5));
    var yr1   = parseInt(ngct.substring(6,10));
    if (yr1 != year)
    {
        alert("Ban nhap nam chua dung!");
        document.getElementById('ngct').focus();
        return;
    }
    var ngay = yr1+"-"+ mon1+"-" + dt1;
//			var a= "";
//			try {
//			 testdate = $.datepicker.parseDate('yy-mm-dd', ngay);
//			 //alert(testdate);
//			} catch (e)
//			{
//			 alert('Ban nhap ngay ' + ngay  + ' khong dung.' );
//			 return;
//			}

    ngct = ngay;


    var hoten=document.getElementById('hoten').value;

    var diachi=document.getElementById('diachi').value;
    var lydo=document.getElementById('lydo').value;
    var emadv = document.getElementById('madv');
    var madv = "";

    if ( emadv != null)
    {
        madv = emadv.value;
    }

    var solgctg= document.getElementById('solgctg').value;

    var etygia = document.getElementById('tygia');
    var tygia = "";
    if ( etygia != null)
    {
        tygia = etygia.value;
    }

    matkas = $("#matk option:selected").text();
    matka = matkas.split("-");
    matk =matka[0];

//		var mant=document.getElementById('mant').value;
//		var madv = document.getElementById('madv').value;
//		var dknont = document.getElementById('dknont').value;
//		var dknovn = document.getElementById('dknovn').value;

    $(".myheaderrow").each(function(i, v){
        $(this).find('th').each(function(ii, vv){
            cautruc[ii] = $(this).attr("name");
        });
    })



    $(".mydatarow").each(function(i, v){
        data[i] = Array();
        cot = 0;
        $(this).find('select').each(function(ii, vv){
            giatri = $("option:selected", this).text();
            giatri = giatri.split("::");
            data[i][cot] = String(giatri[0]);
            cot = cot +1;
        });

        $(this).find('input').each(function(ii, vv){
            if (cautruc[cot].indexOf("sotien") ==0)
            {
                var st = $(this).val();
                var st1 = parseFloat(st.replace(/,/g, ""));
                if (!isNaN(st1))
                {
                    data[i][cot] = st1;
                }
                else
                {
                    data[i][cot] = "";
                }
                cot = cot+1;
            }
            else
            {
                data[i][cot] = $(this).val();
                cot = cot+1;
            }
        });
    })


    jQuery.ajax({
        type: "POST",
        url: urlupdate,
        data: {host: host, username: username, password: password, databaseName: databaseName, journalid:journalid,  year:year,  tableArr: data, cautruc: cautruc, soct: soct, ngct: ngct, hoten:hoten, diachi: diachi, lydo: lydo, madv: madv, solgctg: solgctg, tygia: tygia, matk: matk, mant: mant, mact:mact, noco:noco, idphieu: idphieu},
        cache: false,
        success: function(response)
        {
            //alert(response);
            if (response == "2")
            {
                alert("Khong co du lieu!");
            }
            else if (response == "1")
            {
                alert("Co loi du lieu, mau tin khong ghi duoc!");

            }
            else
            {
                if (idphieu == "")
                {
                    $('div#idphieu').html(response);
                    $('input#print').attr("disabled", false);
                    $('input#save').attr("value", "Thêm mới");
                }
                else
                {
                    // alert("Da ghi xong!");
                }
                $('div#action').html("Xem chứng từ");
                $('input#save').attr("value", "Thêm mới");
                $('input#edit').attr("disabled", false);
                $('input#edit').attr("value", "Sửa");
            }
        },

        error: function(data, errorThrown)
        {
            alert('request failed :'+errorThrown);
        }
    });


}

function Edit_1CT(){

    editmode = $('input#edit').val();
    idphieu = $('div#idphieu').html();
    if (idphieu = ""){
        $('input#save').attr("value", "Ghi lại");
        $('input#edit').attr("disableb", true);
        $('div#action').html("Thêm chứng từ");
    }else
    if (editmode == "Sửa"){
        $('input#save').attr("value", "Ghi lại");
        $('input#edit').attr("value", "Thôi sửa");
        $('div#action').html("Sửa chứng từ");
        addmode = "edit";
    }
    else
    {
        $('input#save').attr("value", "Thêm mới");
        $('input#edit').attr("value", "Sửa");
        $('div#action').html("Xem chứng từ");
    }
}



function editCT(idPhieu, url)
{
    url = url + "&idPhieu=" + encodeURIComponent(idPhieu);
    location.href = url;
    //var win = window.open(url, '_blank');

}

function refurl(url)
{
    location.href = url;

}

function deleCT(host, username, password, databaseName, journalid,  year, idPhieu, soct, url, urlRFR)
{
    if (!(confirm("Ban muon xoa chung tu"+ soct+"  khong?")))
    {
        return;
    }
    var x=document.getElementById('customers');
    for (i=1;i< x.rows.length ; i++)
    {
        var row = x.rows[i];
        var a1 = row.getElementsByTagName('a')[0];
        if (idPhieu == a1.id)
        {
            document.getElementById("customers").deleteRow(i);
        }
    }

    jQuery.ajax({
        type: "POST",
        url: url,
        data: {host: host, username: username, password: password, databaseName: databaseName, journalid: journalid, year:year,  idPhieu:idPhieu},
        cache: false,
        success: function(response)
        {
            location.href = urlRFR;
        },

        error: function(data, errorThrown)
        {
            alert('request failed :'+errorThrown);
        }
    });
    return;

    }

